package com.weimei.conversionTreasure.viewModel;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.app.Activity;
import android.app.Application;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.lxj.xpopup.XPopup;
import com.weimei.conversionTreasure.R;
import com.weimei.conversionTreasure.activity.VipActivity;
import com.weimei.conversionTreasure.http.Repository;
import com.weimei.conversionTreasure.http.entity.BaseResult;
import com.weimei.conversionTreasure.http.entity.FaJiaoDetailBean;
import com.weimei.conversionTreasure.http.entity.PaoLiangDetailBean;
import com.weimei.conversionTreasure.utils.UserUtils;
import com.weimei.conversionTreasure.utils.ValidateUtils;
import com.weimei.conversionTreasure.weight.BottomRulePop;
import com.weimei.conversionTreasure.weight.BottomWheelPop;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AddRecordVM extends BaseViewModel<Repository> {
    Activity mActivity;

    public ObservableField<String> type = new ObservableField<>("1");
    public ObservableField<String> lsType = new ObservableField<>("");
    public ObservableField<String> lsKg = new ObservableField<>("");
    public ObservableField<String> plsw = new ObservableField<>("");
    public ObservableField<String> plsc = new ObservableField<>("");
    public ObservableField<String> plRemaker = new ObservableField<>("");


    public ObservableField<String> fjTitle = new ObservableField<>("");
    public ObservableField<String> fjTx = new ObservableField<>("");
    public ObservableField<String> fjTxgz = new ObservableField<>("");
    public ObservableField<String> fjRemaker = new ObservableField<>("");

    private List<BottomRulePop.RuleBean> mList = new ArrayList<>();


    View mView;

    public void setmActivity(Activity mActivity, View view) {
        this.mActivity = mActivity;
        this.mView = view;
    }

    public AddRecordVM(@NonNull Application application, Repository model) {
        super(application, model);
    }

    public BindingCommand lsTypeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            List<String> list = Arrays.asList(mActivity.getResources().getStringArray(R.array.jiu_str));
            new XPopup.Builder(mActivity)
                    .moveUpToKeyboard(false)//如果不加这个，评论弹窗会移动到软键盘上面
                    .enableDrag(true)
                    .asCustom(new BottomWheelPop(mActivity, list, s1 -> lsType.set(s1)))
                    .show();
        }
    });

    public BindingCommand txRuleClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            new XPopup.Builder(mActivity)
                    .moveUpToKeyboard(false)//如果不加这个，评论弹窗会移动到软键盘上面
                    .enableDrag(true)
                    .asCustom(new BottomRulePop(mActivity, (s, list) -> {
                        fjTxgz.set(s);
                        mList.clear();
                        mList.addAll(list);

                    }))
                    .show();
        }
    });

    public BindingCommand plscClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mView.getWindowToken(), 0); //强制隐藏键盘
            TimePickerView pvTime = new TimePickerBuilder(mActivity, (date, v) -> {
                Log.d("XXXX", date + "");
                plsc.set(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date));
            })
                    .setType(new boolean[]{false, true, true, true, true, false})
                    .setLabel("年", "月", "日", "时", "分", null)
                    .build();
            pvTime.show();
        }
    });

    public BindingCommand txsjClck = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mView.getWindowToken(), 0); //强制隐藏键盘
            TimePickerView pvTime = new TimePickerBuilder(mActivity, (date, v) -> {
                fjTx.set(new SimpleDateFormat("yyyy-MM-dd").format(date));
            })
                    .setType(new boolean[]{false, true, true, false, false, false})
                    .setLabel("年", "月", "日", null, null, null)
                    .build();
            pvTime.show();
        }
    });


    public BindingCommand Save = new BindingCommand(() -> {
        if (!UserUtils.isVip()) {
            ToastUtils.showShort("您还不是会员，请先开通会员后再使用！！！");
            startActivity(VipActivity.class);
            return;
        }
        if (type.get().equals("1")) {
            //泡粮保存
            plSave();
        } else {
            //发酵保存
            fjSave();
        }
    });

    private void fjSave() {
        if (ValidateUtils.isEmptyString(fjTitle.get())) {
            ToastUtils.showShort("请输入标题");
            return;
        }

        if (ValidateUtils.isEmptyString(fjTx.get())) {
            ToastUtils.showShort("请选择下次提醒时间");
            return;
        }

        if (ValidateUtils.isEmptyString(fjTxgz.get())) {
            ToastUtils.showShort("请选择提醒规则");
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("user_id", UserUtils.getUserAccount());
        map.put("title", fjTitle.get());
        map.put("rule", fjTxgz.get());
        map.put("notes", fjRemaker.get());
        switch (mList.size()) {
            case 1:
                map.put("oneDate", mList.get(0).selTime);
                break;
            case 2:
                map.put("oneDate", mList.get(0).selTime);
                map.put("twoDate", mList.get(1).selTime);
                break;
            case 3:
                map.put("oneDate", mList.get(0).selTime);
                map.put("twoDate", mList.get(1).selTime);
                map.put("thereDate", mList.get(2).selTime);
                break;
            case 4:
                map.put("oneDate", mList.get(0).selTime);
                map.put("twoDate", mList.get(1).selTime);
                map.put("thereDate", mList.get(2).selTime);
                map.put("fourDate", mList.get(3).selTime);
                break;
            case 5:
                map.put("oneDate", mList.get(0).selTime);
                map.put("twoDate", mList.get(1).selTime);
                map.put("thereDate", mList.get(2).selTime);
                map.put("fourDate", mList.get(3).selTime);
                map.put("fiveDate", mList.get(4).selTime);
                break;
        }
        model.addFerment(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        ToastUtils.showShort(baseResult.msg);
                        if (baseResult.issucc) {
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void plSave() {
        if (ValidateUtils.isEmptyString(lsType.get())) {
            ToastUtils.showShort("请选择粮食类型");
            return;
        }

        if (ValidateUtils.isEmptyString(lsKg.get())) {
            ToastUtils.showShort("请输入粮食重量");
            return;
        }

        if (ValidateUtils.isEmptyString(plsw.get())) {
            ToastUtils.showShort("请输入泡酒水温");
            return;
        }

        if (ValidateUtils.isEmptyString(plsc.get())) {
            ToastUtils.showShort("请选择泡酒时长");
            return;
        }


        Map<String, String> map = new HashMap<>();
        map.put("user_id", UserUtils.getUserAccount());
        map.put("types", lsType.get());
        map.put("weight", lsKg.get() + "kg");
        map.put("heat", plsw.get() + "°C");
        map.put("time", plsc.get());
        map.put("notes", plRemaker.get());
        model.addSoakgrain(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        ToastUtils.showShort(baseResult.msg);
                        if (baseResult.issucc) {
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getData(String flag, String id) {
        if (flag.equals("0")) {
            getFJData(id);
        } else {
            getPLData(id);
        }
    }

    private void getFJData(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("user_id", UserUtils.getUserAccount());
        map.put("sid", id);
        model.fermentDetails(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<FaJiaoDetailBean>() {
                    @Override
                    public void onNext(FaJiaoDetailBean faJiaoDetailBean) {
                        if (faJiaoDetailBean.issucc)
                            if (ValidateUtils.isNotEmptyObjectOrString(faJiaoDetailBean)) {
                                fjTitle.set(faJiaoDetailBean.getData().getTitle());
                                fjTx.set(faJiaoDetailBean.getData().getOneTime());
                                fjTxgz.set(faJiaoDetailBean.getData().getRule());
                                fjRemaker.set(faJiaoDetailBean.getData().getNots());
                            }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getPLData(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("user_id", UserUtils.getUserAccount());
        map.put("sid", id);
        model.soakgrainInfo(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<PaoLiangDetailBean>() {
                    @Override
                    public void onNext(PaoLiangDetailBean detailBean) {
                        if (detailBean.issucc)
                            if (ValidateUtils.isNotEmptyObjectOrString(detailBean)) {
                                lsType.set(detailBean.getData().getFoodType());
                                lsKg.set(detailBean.getData().getFoodWeight());
                                plsw.set(detailBean.getData().getFoodHeat());
                                plsc.set(detailBean.getData().getFoodDuration());
                                plRemaker.set(detailBean.getData().getNotes());
                            }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
